from flask import Flask,request
from manager_mysql import ToDoManagerMysql
from todo import Todo

app = Flask(__name__)

app.config['JSON_AS_ASCII'] = False


manager = ToDoManagerMysql()
manager.init_db()

@app.route('/')
def index():
    return '<h1>Hello</h1>'

@app.route('/todos',methods=['GET'])
def get_todo_list():
    return {'todos':[x.__dict__ for x in manager.list_todos()]}


@app.route('/todos',methods=['POST'])
def create_todo():
    print(request.form)
    if 'title' not in request.form:
        return '参数错误，请提供title参数',400
    todo = manager.create(request.form["title"])

# @app.route('/todos', methods=['POST'])
# def create_todo():
#     print(request.json)
#     if 'title' not in request.json:
#         return '参数错误，请提供title参数', 400
#     todo = Todo(request.json['title'])
#     todo_list.append(todo)

    return todo.__dict__

@app.route("/todos/mark_completed", methods=['GET'])
def mark_completed():
    """
    创建待办事项接口
        参数： title，表示待办事项的内容
        成功，返回已创建的待办事项 JSON 表示
    """
    if 'todo_id' not in request.args:
        return '参数错误，必须提供 todo_id 参数', 400
    id = int(request.args['todo_id'])
    todo = manager.mark_completed(id)
    if todo is not None:
        return todo.__dict__
    else:
        return f'todo not found, todo_id={id}', 404


if __name__ == '__main__':
    app.run()